<template>
	<view>
		<u-popup :show="deviceConfig.showPopup" mode="center" :closeOnClickOverlay="false" :round="20"
			bgColor="transparent" @close="close_device_popup">
			<view class="f-dc" v-if="deviceConfig.showPopup"
				style="width: 80vw;max-height: 70vh;min-height: 400px;background-color: #fff;border-radius: 20px;">
				<view class="x-c" style="padding: 20px;">
					<view class="x-f">
						<u-icon name="arrow-leftward" color="#333" size="24" @click="close_device_popup"></u-icon>

						<text style="margin-left: 4px;font-size: 12px;" v-if="deviceConfig.setName">返回</text>
					</view>
					<view class="x-c" style="flex: 1;">
						<text v-if="!deviceConfig.setName"
							style="font-size: 18px;">{{deviceConfig.tempDeviceInfo.aliasName || deviceConfig.tempDeviceInfo.name}}</text>
						<text v-else style="font-size: 18px;">设置别名</text>

					</view>
					<view class="x-ec">
						<template v-if="!deviceConfig.setName">
							<m-bubble type="list" :selectData="deviceConfig.formMenus" position="right"
								topOpsotion="right" bgcRgba="#fff" color="#333" @selectFun="deviceConfig_popup_menu">
								<u-icon name="list-dot" color="#333" size="28"></u-icon>
							</m-bubble>
						</template>
					</view>

				</view>

				<template v-if="!deviceConfig.setName">


					<!-- 蓝牙设备 -->
					<template v-if="deviceConfig.tempDeviceInfo.config.Communication == 'Bluetooth'">

						<template v-if="deviceConfig.bluetoothType">

							<view class="flex-auto f-dc" style="padding: 0 20px;font-size: 14px;">
								<view style="padding: 10px 0;">
									<text
										style="font-size: 20px;color: #000;font-weight: 600;">{{deviceConfig.tempDeviceInfo.config.MeasureName}}</text>
								</view>

								<view style="padding: 10px 0;">
									<text>{{deviceConfig.tempDeviceInfo.config.MeasureSpec}}</text>
									<text style="margin: 0 2px;">·</text>
									<text :style="{
								color: deviceConfig.tempDeviceInfo.connected ? '#05bc4f' : '#999'
								}">{{deviceConfig.tempDeviceInfo.connected ? '已连接' : '未连接'}}</text>
								</view>

								<view class="x-f" style="padding: 10px 0;">
									<view>
										<text>设备类型：</text>
									</view>

									<view>
										<text>{{deviceConfig.tempDeviceInfo.config.Communication}}</text>
									</view>
								</view>

								<view class="x-f" style="padding: 10px 0;">
									<view>
										<text>信号强度：</text>
									</view>

									<view>
										<template v-if="deviceConfig.showLoading">
											<text>正在扫描设备...</text>
										</template>

										<template v-else>
											<volume v-if="deviceConfig.findDevice" :num="deviceConfig.RSSI"></volume>

											<template v-else>
												<text>请确认设备蓝牙是否开启</text>
											</template>
										</template>
									</view>
								</view>

							</view>


							<view class="x-c" style="padding: 20px;">
								<button style="width: 90%;" @click="handlerClickByLink"
									:loading="deviceConfig.showLoading" :disabled="deviceConfig.showLoading"
									type="primary">{{deviceConfig.tempDeviceInfo.connected ? "断开连接" 
								: !deviceConfig.findDevice ?"刷新" 
								: deviceConfig.showLoading ? "扫描中" 
								: "连接设备"}}</button>
							</view>
						</template>

						<u-empty v-else text="开启蓝牙,以便查找附近蓝牙设备" iconSize="150" icon="/static/tabbar-icons/Bluetooth.png"
							style="height: 100%;">
							<u-button @click="openBluetoothAdapter" size="small" type="primary"
								:style="{marginTop:10+'px'} " text="立即开启"></u-button>
						</u-empty>
					</template>

				</template>

				<template v-else>
					<view class="flex-auto" style="padding: 0 20px;font-size: 14px;">
						<u-input placeholder="请输入别名" border="bottom" inputAlign="center" :focus="true"
							v-model="deviceConfig.changeName" suffixIcon="edit-pen-fill"></u-input>
					</view>


					<view class="x-ac" style="padding: 20px;">
						<button style="flex: 1;margin: 0 10px;" @click="handlerSetDeviceName(0)" type="primary"
							plain="">重置别名</button>
						<button style="flex: 1;margin: 0 10px;" @click="handlerSetDeviceName(1)"
							type="primary">设置别名</button>
					</view>
				</template>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import Volume from "@/st_qms/control/Device/signal.vue";
	export default {
		components: {
			Volume
		},
		data() {
			return {
				deviceConfig: {
					showPopup: true,
					formMenus: [{
						name: '取消配对',
						value: '',
						icon: 'close-circle',
						show: true,
					}, {
						name: '设置别名',
						value: '',
						icon: 'setting',
						show: true,
					}, ],
					setName: false,
					changeName: "",
					tempDeviceInfo: {},
					bluetoothType: false, // 蓝牙适配器是否开启
					RSSI: 0,


					findDevice: false, // 是否查询到设备
					showLoading: false,
					scanTimer: null
				},
				choiceDeviceId: null,
				eventChannel: null
			}
		},
		computed: {

			getConnectedDevices() {
				if (this.choiceDeviceId) {
					const data = this.$store.state.bluetooth.connectedDevices;
					return this.$store.state.bluetooth.connectedDevices[this.choiceDeviceId];
					console.log(data);

				} else {
					return {};
				};
			},
			adapterState() { // 获取当前蓝牙适配器状态
				console.log(this.$store.state.bluetooth.adapterState);
				return this.$store.state.bluetooth.adapterState.available;
			}
		},
		watch: {
			// 监听蓝牙适配器状态
			adapterState: {
				async handler(nval, oval) {
					// 判断设备弹层是否打开，
					if (nval && !oval && this.deviceConfig.showPopup) {
						this.$bluetooth.isDiscovering = false;
						const initBackInfo = await this.$bluetooth.openBluetooth();
						// this.deviceConfig.bluetoothType = true;
						console.log(initBackInfo);
						if (initBackInfo.status == 0) {
							// 初始化蓝牙
							// this.initBluetoothInfo();
						} else {

							this.deviceConfig.bluetoothType = false;
						}
					}
				},
				deep: true,
			}
		},
		created() {
			this.eventChannel = this.getOpenerEventChannel();


		},
		async onLoad(option) {
			let that = this;
			console.log(option.deviceId);
			this.choiceDeviceId = option.deviceId;

			console.log(this.getConnectedDevices);

			this.$set(this.deviceConfig, "tempDeviceInfo", this.getConnectedDevices);

			// 强制初始化蓝牙信息
			const initBackInfo = await this.$bluetooth.openBluetooth();
			if (initBackInfo.status == 0) {
				// 初始化蓝牙
				this.initBluetoothInfo();
			} else {

				this.deviceConfig.bluetoothType = false;
			}

		},
		mounted() {
			let that = this;

		},
		onUnload() {
			this.stopScan();
		},
		methods: {
			async initBluetoothInfo() {
				let that = this;
				try {

					this.deviceConfig.bluetoothType = true;
					const linkType = await this.$bluetooth.isConnected(this.deviceConfig.tempDeviceInfo.deviceId);
					console.log(linkType);
					// 判断当前设备是否连接
					if (!linkType) { // 未连接
						// 开启扫描
						this.deviceConfig.findDevice = true;
						this.deviceConfig.showLoading = true;
						this.startScan();
					} else {
						this.deviceConfig.showLoading = false;
					}
				} catch (error) {
					console.log(error);
					if (error.code == "10001") {
						this.deviceConfig.bluetoothType = false;
					}
				}
			},
			startScan() {
				let that = this;
				// 清除可能存在的旧计时器，避免重复计时
				if (this.deviceConfig.scanTimer) {
					clearInterval(this.deviceConfig.scanTimer);
					this.deviceConfig.scanTimer = null;
				}

				// 重置扫描状态
				this.deviceConfig.showLoading = true; // 显示加载中
				this.deviceConfig.findDevice = false; // 标记是否在本轮5秒内找到设备
				let currentSecond = 0; // 当前计时秒数

				// 启动蓝牙扫描
				this.$bluetooth.startDiscovery(devices => {
					// 过滤出目标设备（根据设备ID匹配）
					const targetDevice = devices.find(
						item => item.deviceId === that.deviceConfig.tempDeviceInfo.deviceId
					);

					if (targetDevice) {
						// 找到设备：更新信号强度，标记本轮已找到
						that.$set(that.deviceConfig, "RSSI", targetDevice.RSSI);
						that.deviceConfig.findDevice = true; // 关键：标记本轮找到设备
						that.deviceConfig.showLoading = false; // 隐藏加载中
					}
				});

				// 启动5秒计时器（每秒检查一次）
				this.deviceConfig.scanTimer = setInterval(() => {
					currentSecond++; // 每秒累加

					// 当计时达到5秒时
					if (currentSecond >= 5) {
						if (that.deviceConfig.findDevice) {
							// 情况1：本轮5秒内找到设备 → 重置计时，进入下一轮5秒
							uni.hideLoading();
							currentSecond = 0; // 重置秒数
							that.deviceConfig.findDevice = false; // 重置标记（等待下一轮判断）
							console.log("找到设备，进入下一轮5秒扫描");
						} else {
							uni.hideLoading();
							// 情况2：本轮5秒内未找到设备 → 停止扫描
							clearInterval(that.deviceConfig.scanTimer); // 清除计时器
							that.deviceConfig.scanTimer = null;
							that.deviceConfig.showLoading = false; // 隐藏加载中
							that.deviceConfig.findDevice = false; // 标记未找到
							that.stopScan(); // 停止蓝牙扫描
							console.log("5秒未找到设备，已停止扫描");
						}
					}
				}, 1000); // 每秒执行一次检查
			},
			// 停止扫描
			stopScan() {
				this.$bluetooth.stopDiscovery();
			},

			close_device_popup() {
				let that = this;
				if (this.deviceConfig.setName) {
					this.deviceConfig.setName = false;
					this.deviceConfig.changeName = "";
					return;
				}

				// 停止扫描和计时器
				if (this.deviceConfig.scanTimer) {
					clearInterval(this.deviceConfig.scanTimer);
					this.deviceConfig.scanTimer = null;
				}
				this.stopScan();

				// uni.navigateBack();
				uni.navigateBack({
					delta: 1,
					success() {
						that.eventChannel.emit("cancel", "back");
					}
				})
			},
			deviceConfig_popup_menu(data) { // 点击弹层气泡
				switch (data.name) {
					case "取消配对":
						// 1、断开连接
						this.$bluetooth.disconnectDevice(this.deviceConfig.tempDeviceInfo.deviceId);

						const deviceInfo = this.$utils.deepClone(this.$store.state.bluetooth.connectedDevices);
						// 2、删除设备信息
						Object.keys(deviceInfo).forEach(item => {
							delete deviceInfo[this.deviceConfig.tempDeviceInfo.deviceId]
						});


						this.$store.commit("bluetooth/ChangeAndSetStateData", {
							Name1: 'connectedDevices',
							data: deviceInfo,
							StorageName: "connectedDevices",
							StorageData: JSON.stringify(deviceInfo)
						});

						// 关闭弹层
						this.close_device_popup();

						break;

					case "设置别名":

						this.deviceConfig.setName = true;
						this.deviceConfig.changeName = this.deviceConfig.tempDeviceInfo.aliasName ? this.deviceConfig
							.tempDeviceInfo.aliasName : this.deviceConfig.tempDeviceInfo.name;


						break;
					default:
						break;
				}
			},
			async handlerClickByLink() { // 点击按钮搜索并连接
				let that = this;
				const deviceType = this.deviceConfig.tempDeviceInfo.connected;

				switch (deviceType) {
					case true:
						uni.showLoading({
							title: "正在断开"
						})
						// 断开设备
						this.$bluetooth.disconnectDevice(this.deviceConfig.tempDeviceInfo.deviceId, () => {
							uni.hideLoading();
							// 重新设置蓝牙状态
							this.deviceConfig.tempDeviceInfo.connected = false;
							// 开启扫描
							this.startScan();
						});

						break;
					case false:
						// 判断是否查询到设备
						if (this.deviceConfig.findDevice) {
							// 连接设备
							uni.showLoading({
								title: "正在连接"
							})
							console.log(this.deviceConfig.tempDeviceInfo);
							this.$bluetooth.connectDevice(this.deviceConfig.tempDeviceInfo, this.deviceConfig
								.tempDeviceInfo.config, () => {
									uni.hideLoading();

									that.deviceConfig.showLoading = false;
									that.deviceConfig.tempDeviceInfo.connected = true;


									if (that.deviceConfig.scanTimer) {
										clearInterval(that.deviceConfig.scanTimer);
									}
									that.stopScan();

								});

						} else {
							// 连接设备
							uni.showLoading({
								title: "正在扫描"
							})
							// 未查询到，刷新重试
							this.initBluetoothInfo();

						}

						break;
					default:
						break;
				}
			},
			openBluetoothAdapter() {

				let sysDeviceInfo = JSON.parse(uni.getStorageSync('sysDeviceInfo'));
				console.log(sysDeviceInfo);
				if (sysDeviceInfo['osName'] == 'ios') {} else if (sysDeviceInfo['osName'] == 'android') {
					// Native.js for Android封装一条通过JS语法直接调用Native Java接口通道，通过plus.android可调用几乎所有的系统API
					const BluetoothAdapter = plus.android.importClass(
						'android.bluetooth.BluetoothAdapter'); // 引入Java 蓝牙类
					const blueadapter = BluetoothAdapter.getDefaultAdapter(); //拿到默认蓝牙适配器方法
					console.log(blueadapter);
					if (blueadapter) {
						setTimeout(() => {
							// 判断蓝牙是否开启
							if (blueadapter.isEnabled()) {
								console.log('开启')

							} else {
								// 尝试开启蓝牙（Android原生方法）
								const isOpened = blueadapter.enable(); // 返回boolean，true表示开启成功（部分设备可能需要用户确认）
								console.log('开启结果：', isOpened);
							}
						}, 50)
					}
				}
			},
			handlerSetDeviceName(str) {
				let that = this;
				console.log(that.deviceConfig.tempDeviceInfo.deviceId);
				console.log(this.deviceConfig.changeName);

				let title = str == 1 ? "是否确认设置" : "是否确认重置"

				this.$utils.layer.confirm(title, (ret) => {
					const {
						action
					} = ret;
					console.log(action);

					if (action == "confirm") {
						let lastName = ""
						if (str == 1) {
							lastName = that.deviceConfig.changeName
						} else {
							lastName = that.deviceConfig.tempDeviceInfo.name
						}

						that.$bluetooth.setDeviceAlias(that.deviceConfig.tempDeviceInfo.deviceId, lastName);

					}
					that.deviceConfig.setName = false;
					that.deviceConfig.changeName = "";

					that.eventChannel.emit("setName");
				})


			},
		}
	}
</script>

<style lang="scss">
	page {
		background: transparent;
		height: 100vh;
	}
</style>